package me.zhengjie.modules.forecast.satview;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

public class SatViewDataServiceImpl {
    private static Log log = LogFactory.getLog(SatViewDataServiceImpl.class);

    /**
     * 风云天地数值预报基本数据单点接口.
     * @param obsDate
     * @param longitude
     * @param latitude
     * @param types
     * @param gridSource EC，WRF
     * @param validHour 9，24，30
     * @return 返回值四舍五入取整
     */
    public Map<String, Integer> getPointGrid(String obsDate, Double longitude,
            Double latitude, String types, String gridSource, int validHour) {

        try {

            Client client = ClientBuilder.newClient();

            WebTarget webTarget = client
                    .target("http://172.18.18.15:8888/interface/nwp/gridApi/")
                    .path("pointGrid")
                    // .queryParam("obsDate", obsDate)
                    .queryParam("x", Double.toString(longitude))
                    .queryParam("y", Double.toString(latitude))
                    .queryParam("types", types).queryParam("grid", gridSource);

            Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);

            Response response = invocationBuilder.get();

            String output2 = response.readEntity(String.class);

            log.info("\n============getPointGrid============");
            log.info(output2);
            // return output2;

            // PointGrid output2 = response.readEntity(PointGrid.class);

            ObjectMapper objectMapper = new ObjectMapper();
            // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            // false);
            try {
                // PointGrid pointGrid = objectMapper.readValue(output2,
                // PointGrid.class);
                Map<String, Object> pointGrid = objectMapper.readValue(output2, Map.class);
                log.info("pointGrid = " + pointGrid);

                Object elements = ((Map) pointGrid.get("data")).get("data");
                ArrayList datas = (ArrayList) elements;
                for (int i = 0; i < datas.size(); i++) {
                    Map element = (Map) datas.get(i);
                    if (element.get("key").equals("WIND")) {
                        // ArrayList times = (ArrayList)element.get("times");
                        Map temp = (Map) element.get("data");
                        ArrayList<Double> ws = (ArrayList<Double>) temp.get("ws");
                        ArrayList<Double> dir = (ArrayList<Double>) temp.get("dir");

//                        ArrayList<Double> subWs, subDir;
//                        switch (validHour) {
//                        case 9:
//
//                        }
                        Double wsAverage = ws.subList(0, validHour).stream()
                                .mapToDouble(Double::doubleValue).average()
                                .getAsDouble();
//                        Double dirAverage = dir.subList(0, validHour).stream()
//                                .mapToDouble(Double::doubleValue).average()
//                                .getAsDouble();
                        Double dirAverage = average(dir.subList(0, validHour));

                        Map<String, Integer> result = new HashMap<String, Integer>();
                        result.put("ws", Integer.valueOf((int) Math.round(wsAverage)));
                        result.put("dir", Integer.valueOf((int) Math.round(dirAverage)));
                        return result;
                    }
                }
            } catch (IOException e) {
                log.error(e);
                return null;
            }

        } catch (Exception e) {
            log.error(e);
            return null;
        }
        return null;
    }
    
    /**
     * 按向量计算风向平均值
     * Method description goes here.
     * @param windDirs
     * @return
     */
    Double average(List<Double> windDirs) {
        Double sumOfSin = 0D;
        Double sumOfCos = 0D;
        for (Double wd : windDirs) {
            sumOfSin += Math.sin(Math.toRadians(wd));
            sumOfCos += Math.cos(Math.toRadians(wd));
        }
        Double avg = Math.toDegrees(Math.atan(sumOfSin / sumOfCos));
        if (avg <= 0d) {
            return 360 + avg;
        } else {
            return avg;
        }
    }

    public static void main(String[] args) {
        SatViewDataServiceImpl svdsi = new SatViewDataServiceImpl();
        // svdsi.getPointGrid(new Date(), 126D, 45D, "T2,WIND", "EC");
        Map<String, Integer> result = svdsi.getPointGrid("2019-11-24 00:00:00",
                130D, 24D, "T2,WIND", "EC", 9);
        log.info(result);
    }
}